package cn.dansj.common.utils.crypt;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * AES 对称算法加密/解密工具类
 */
public abstract class AesUtils {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";

    // 加密（返回Base64格式的IV+密文）
    public static String encrypt(String data, String aesKey) throws Exception {
        SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] ivBytes = cipher.getIV(); // 自动生成16字节IV
        byte[] encryptedBytes = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(combineIvAndData(ivBytes, encryptedBytes));
    }

    // 解密（处理含IV的Base64字符串）
    public static String decrypt(String encryptedData, String aesKey) throws Exception {
        byte[] fullData = Base64.getDecoder().decode(encryptedData);
        byte[] ivBytes = new byte[16];
        byte[] cipherBytes = new byte[fullData.length - 16];
        System.arraycopy(fullData, 0, ivBytes, 0, 16);
        System.arraycopy(fullData, 16, cipherBytes, 0, cipherBytes.length);

        SecretKeySpec key = new SecretKeySpec(aesKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));
        return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
    }

    private static byte[] combineIvAndData(byte[] iv, byte[] data) {
        byte[] combined = new byte[iv.length + data.length];
        System.arraycopy(iv, 0, combined, 0, iv.length);
        System.arraycopy(data, 0, combined, iv.length, data.length);
        return combined;
    }
}